
package com.jf.cloud.delivery.controller.app;

import com.jf.cloud.api.delivery.dto.StationSalesDTO;
import com.jf.cloud.api.feign.SearchOrderFeignClient;
import com.jf.cloud.api.order.constant.OrderStatus;
import com.jf.cloud.api.order.feign.OrderFeignClient;
import com.jf.cloud.api.order.feign.OrderSelfStationFeignClient;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.dto.OrderSearchDTO;
import com.jf.cloud.common.order.dto.OrderVirtualInfoDTO;
import com.jf.cloud.common.order.vo.EsOrderVO;
import com.jf.cloud.common.order.vo.OrderSelfStationVO;
import com.jf.cloud.common.order.vo.OrderVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.delivery.dto.StationDTO;
import com.jf.cloud.delivery.model.Station;
import com.jf.cloud.delivery.service.StationService;
import com.jf.cloud.api.delivery.vo.StationVO;
import com.jf.cloud.delivery.vo.StationDetailVO;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 自提点信息
 *
 * @author zz
 * @date 2020-12-07 15:10:01
 */
@RestController("appStationController")
@RequestMapping("/station")
@Tag(name = "用户自提点信息")
public class StationController {

    @Autowired
    private StationService stationService;

    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private SearchOrderFeignClient searchOrderFeignClient;

    @Autowired
    private OrderSelfStationFeignClient orderSelfStationFeignClient;

    @Autowired
    private OrderFeignClient orderFeignClient;
    @GetMapping("/page")
    @Operation(summary = "获取自提点信息列表" , description = "分页获取自提点信息列表")
    public ServerResponseEntity<PageVO<StationVO>> page(@Valid PageDTO pageDTO) {
        PageVO<StationVO> stationPage = stationService.page(pageDTO);
        return ServerResponseEntity.success(stationPage);
    }

    @GetMapping
    @Operation(summary = "获取自提点信息" , description = "根据stationId获取自提点信息")
    public ServerResponseEntity<StationVO> getInfo() {
        Long stationId = AuthUserContext.get().getTenantId();
        return ServerResponseEntity.success(stationService.getByStationId(stationId));
    }

    @PutMapping
    @Operation(summary = "更新自提点信息" , description = "更新自提点信息")
    public ServerResponseEntity<Void> update(@Valid @RequestBody StationDTO stationDTO) {
        Station station = mapperFacade.map(stationDTO, Station.class);
        station.setStationId(AuthUserContext.get().getTenantId());
        station.setAccount(null);
        stationService.update(station);
        return ServerResponseEntity.success();
    }

    @DeleteMapping
    @Operation(summary = "删除自提点信息" , description = "根据自提点信息id删除自提点信息")
    public ServerResponseEntity<Void> delete(@RequestParam Long stationId) {
        stationService.deleteById(stationId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/get_station_index_info")
    @Operation(summary = "自提点首页数据", description = "获取自提点首页数据")
    public ServerResponseEntity<StationVO> getStationIndexInfo() {
        Long stationId = AuthUserContext.get().getTenantId();
        StationVO stationVO = stationService.getByStationId(stationId);
        List<StationSalesDTO> stationSalesRecord = stationService.getStationSalesRecord(stationVO.getShopId(), stationId);
        stationVO.setStationSalesDTOList(stationSalesRecord);
        return ServerResponseEntity.success(stationVO);
    }

    @GetMapping("/user_station")
    @Operation(summary = "获取距离用户近的自提点")
    @Parameters({
            @Parameter(name = "lat", description = "纬度", required = true),
            @Parameter(name = "lng", description = "经度", required = true),
            @Parameter(name = "stationName", description = "自提点名字"),
            @Parameter(name = "shopId", description = "店铺id")
    })
    public ServerResponseEntity<PageVO<StationDetailVO>> getStationList(@RequestParam(value = "lat",required = false) Double lat,
                                                                      @RequestParam(value = "lng",required = false) Double lng,
                                                                      @RequestParam("stationName") String stationName,
                                                                      @RequestParam("shopId") Long shopId,
                                                                      PageDTO page) {
        PageVO<StationDetailVO> stationParams = stationService.getStationList(lat, lng, stationName, shopId, AuthUserContext.get().getUserId(), page);
        return ServerResponseEntity.success(stationParams);
    }

    @GetMapping("/order_list_by_status")
    @Operation(summary = "订单列表信息", description = "根据订单状态获取订单列表信息，状态为0时获取所有订单")
    @Parameters({
            @Parameter(name = "status", description = "订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败"),
    })
    public ServerResponseEntity<EsPageVO<EsOrderVO>> orderListByStatus(@ParameterObject OrderSearchDTO orderSearchDTO) {
        Long stationId = AuthUserContext.get().getTenantId();
        orderSearchDTO.setStationId(stationId);
        if(Objects.equals(orderSearchDTO.getStatus(), OrderStatus.PAYED.value())){
            orderSearchDTO.setWaitPurchase(0);
        }
        EsPageVO<EsOrderVO> data = searchOrderFeignClient.pageOrder(orderSearchDTO).getData();
        return ServerResponseEntity.success(data);
    }

    @GetMapping("/get_code")
    @Operation(summary = "自提点二维码信息", description = "自提点二维码信息")
    public ServerResponseEntity<String> getCode() {
        Long stationId = AuthUserContext.get().getTenantId();
        StationVO station = stationService.getStationInfoById(stationId);
        String code = station.getShopId() + "#station#" + stationId;
        return ServerResponseEntity.success(code);
    }

    @GetMapping("/get_station_order_by_code")
    @Operation(summary = "通过提货码获取自提订单或虚拟订单", description = "自提点输入提货码获取自提订单或虚拟订单")
    @Parameter(name = "code", description = "提货码", required = true)
    public ServerResponseEntity<OrderVO> getStationOrderByCode(@RequestParam(value = "code", required = true) String code) {
        ServerResponseEntity<OrderVO> order = orderSelfStationFeignClient.getOrderByStationCode(AuthUserContext.get().getTenantId(), code);
        if (order.isSuccess()){
            return ServerResponseEntity.success(order.getData());
        }else {
            throw new LuckException(order.getMsg());
        }
    }


    @PutMapping("/order_station_by_order_id")
    @Operation(summary = "自提点提货", description = "自提点提货操作")
    @Parameter(name = "orderIds", description = "订单编号数组", required = true)
    public ServerResponseEntity<Boolean> orderStationByOrderId(@RequestBody String orderIds) {
        List<String> orderIdList = Arrays.asList(orderIds.split(","));
        List<Long> ids = new ArrayList<>();
        orderIdList.forEach(s-> ids.add(Long.parseLong(s)));
        ServerResponseEntity<Boolean> responseEntity = orderFeignClient.orderStationByOrderId(ids, AuthUserContext.get().getTenantId());
        if (responseEntity.isSuccess()){
            return ServerResponseEntity.success(responseEntity.getData());
        }else {
            throw new LuckException(responseEntity.getMsg());
        }
    }

    @PutMapping("/order_write_off_by_order_id")
    @Operation(summary = "虚拟商品订单核销操作" , description = "虚拟商品订单核销操作")
    public ServerResponseEntity<Boolean> orderWriteOffByOrderId(@RequestBody OrderVirtualInfoDTO orderVirtualInfoDTO) {
        Long orderId = orderVirtualInfoDTO.getOrderId();
        Long stationId = AuthUserContext.get().getTenantId();
        if (Objects.isNull(orderId)) {
            // 订单不存在
            throw new LuckException("订单不存在");
        }
        ServerResponseEntity<Boolean> responseEntity = orderFeignClient.orderWriteOffByOrderId(orderVirtualInfoDTO, orderId, stationId);
        if (responseEntity.isSuccess()){
            return ServerResponseEntity.success(responseEntity.getData());
        }else {
            throw new LuckException(responseEntity.getMsg());
        }
    }

}
